package com.cqndt.disaster.device.sys.service.impl;

import com.cqndt.disaster.device.dao.data.TabAreaMapper;
import com.cqndt.disaster.device.entity.data.TabArea;
import com.cqndt.disaster.device.sys.dao.SysMenuMapper;
import com.cqndt.disaster.device.sys.dao.SysUserMapper;
import com.cqndt.disaster.device.sys.service.SysUserService;
import com.cqndt.disaster.device.sys.shiro.ShiroUtils;
import com.cqndt.disaster.device.sys.vo.SysUserVo;
import com.cqndt.disaster.device.util.Constant;
import com.cqndt.disaster.device.util.Result;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created By marc
 * Date: 2019/3/8  9:46
 * Description:用户管理
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private TabAreaMapper tabAreaMapper;

    @Override
    @Transactional(propagation=Propagation.REQUIRED)
    public void save(SysUserVo sysUserVo) throws Exception {
        String salt = RandomStringUtils.randomAlphanumeric(20);
        sysUserVo.setSalt(salt);
        sysUserVo.setCreateTime(new Date());
        //密码加密
        sysUserVo.setPassword(ShiroUtils.sha256(sysUserVo.getPassword(), sysUserVo.getSalt()));
        sysUserMapper.save(sysUserVo);
        if(null != sysUserVo.getLabelName1() && !"".equals(sysUserVo.getLabelName1())){
            String[] labelName1s = sysUserVo.getLabelName1().split(",");
            for (String labelName1:labelName1s) {
                sysUserMapper.saveTabUserRole(sysUserVo.getId().toString(),labelName1);
            }
        }
        if(null != sysUserVo.getLabelName2() && !"".equals(sysUserVo.getLabelName2())){
            String[] labelName2s = sysUserVo.getLabelName2().split(",");
            for (String labelName2:labelName2s) {
                sysUserMapper.saveTabUserArea(sysUserVo.getId().toString(),labelName2);
                //新增区划图保存
                TabArea tabArea = tabAreaMapper.selectByPrimaryKey(Integer.parseInt(labelName2));
                sysUserMapper.saveTabMapservice(sysUserVo.getId().toString(),null!=tabArea.getXzqhurl()?tabArea.getXzqhurl():"");
           }
        }
    }

    @Override
    @Transactional(propagation=Propagation.REQUIRED)
    public void update(SysUserVo sysUserVo) throws Exception {
        sysUserMapper.update(sysUserVo);
        sysUserMapper.deleteTabUserRole(sysUserVo.getId().toString());
        sysUserMapper.deleteTabUserArea(sysUserVo.getId().toString());
        sysUserMapper.deleteTabMapservice(sysUserVo.getId().toString());
        if(null != sysUserVo.getLabelName1() && !"".equals(sysUserVo.getLabelName1())){
            String[] labelName1s = sysUserVo.getLabelName1().split(",");
            for (String labelName1:labelName1s) {
                sysUserMapper.saveTabUserRole(sysUserVo.getId().toString(),labelName1);
            }
        }
        if(null != sysUserVo.getLabelName2() && !"".equals(sysUserVo.getLabelName2())){
            String[] labelName2s = sysUserVo.getLabelName2().split(",");
            for (String labelName2:labelName2s) {
                sysUserMapper.saveTabUserArea(sysUserVo.getId().toString(),labelName2);
                //新增区划图保存
                TabArea tabArea = tabAreaMapper.selectByPrimaryKey(Integer.parseInt(labelName2));
                sysUserMapper.saveTabMapservice(sysUserVo.getId().toString(),null!=tabArea.getXzqhurl()?tabArea.getXzqhurl():"");
            }
        }

    }
    @Override
    public Result checkValidate(SysUserVo sysUserVo,Integer flag){
        Result result = new Result();
        boolean isUpdate = false;
        if(flag == 1){
            SysUserVo vo = sysUserMapper.getTabUserById(sysUserVo.getId());
            isUpdate = vo.getUserName().equals(sysUserVo.getUserName());
        }
        if(!isUpdate){
            int num = sysUserMapper.checkValidate1(sysUserVo);
            if(num>0){
                return result.failure(-2,"用户名不能重复");
            }
        }
        return result;
    }
    @Override
    public SysUserVo getTabUserById(Long id){
        SysUserVo result = sysUserMapper.getTabUserById(id);
        return result;
    }
    @Override
    public void delete(String id){
        String[] ids = id.split(",");
        for (String idStr:ids) {
            sysUserMapper.delete(Integer.parseInt(idStr));
            //删除用户区域关联表
            sysUserMapper.deleteTabUserArea(idStr);
            //删除用户角色关联表
            sysUserMapper.deleteTabUserRole(idStr);
            //删除行政区域图
            sysUserMapper.deleteTabMapservice(idStr);
        }
    }
    @Override
    public List<SysUserVo> list(SysUserVo sysUserVo) {
        return  sysUserMapper.list(sysUserVo);
    }
    @Override
    public List<Map<String,Object>> listTabStaticType(SysUserVo sysUserVo){
        return  sysUserMapper.listTabStaticType(sysUserVo);
    }


    @Override
    public List<SysUserVo> listTabRoleAll(SysUserVo sysUserVo){
        return  sysUserMapper.listTabRoleAll(sysUserVo);
    }
    @Override
    public List<SysUserVo> listTabAreaAll(SysUserVo sysUserVo){
        return  sysUserMapper.listTabAreaAll(sysUserVo);
    }

    @Override
    public List<SysUserVo> listTabRoleSelect(Integer id){
        return  sysUserMapper.listTabRoleSelect(id);
    }
    @Override
    public List<SysUserVo> listTabAreaSelect(Integer id){
        return  sysUserMapper.listTabAreaSelect(id);
    }

    @Override
    public List<String> queryPermsForUser(Long userId) {
        List<String> permsList;
        if(userId.toString().equals(Constant.SUPER_ADMIN.toString())){
            permsList = sysMenuMapper.queryPermsForAdmin();
        }else{
            permsList = sysMenuMapper.queryPermsForUser(userId.toString());
        }
        return permsList;
    }

    @Override
    public Result upPassword(Long userId, String oldPass, String newPass) {
        Result result = new Result();
        SysUserVo vo =  sysUserMapper.getTabUserById(userId);
        String oldChPass = ShiroUtils.sha256(oldPass, vo.getSalt());
        if(!oldChPass.equals(vo.getPassword())){
            return result.failure(-1,"原密码输入错误");
        }
        vo.setPassword(ShiroUtils.sha256(newPass, vo.getSalt()));
        sysUserMapper.update(vo);
        return result.success("修改成功");
    }

    @Override
    public Result resetPass(Long userId, String newPass) {
        Result result = new Result();
        if(null == userId){
            return result.failure(-1,"重置密码对象id为空");
        }
        SysUserVo vo =  sysUserMapper.getTabUserById(userId);
        if(null == vo){
            return result.failure(-1,"重置密码对象为空");
        }
        String pass = ShiroUtils.sha256(newPass, vo.getSalt());
        vo.setPassword(pass);
        sysUserMapper.update(vo);
        result.setData(pass);
        return result.success("重置成功");
    }

    @Override
    public String getAreaIdByUserId(Long userId) {
        return sysUserMapper.getAreaIdByUserId(userId);
    }

    @Override
    public Result assignProjectList(SysUserVo vo) {
        Result result = new Result();
        if(null == vo.getId()){
            return result.failure(-1,"分配对象不存在");
        }
        SysUserVo userVo =  sysUserMapper.getByUserNameAndPass(vo);
        if(null == userVo){
            return result.failure(-1,"分配对象不存在");
        }
        List<Map<String,Object>> list = sysUserMapper.assignProjectList(userVo);
        result.setData(list);
        return result;
    }

    @Override
    public Result assignedProjectList(Long id) {
        List<Map<String,Object>> list = sysUserMapper.assignedProjectList(id.toString());
        return new Result().success(list);
    }

    @Override
    public Result assignProject(Long id, String projectIds) {
        Result result = new Result();
        if(null == id){
            return result.failure(-1,"请选择一个用户分配");
        }
        SysUserVo userVo =  sysUserMapper.getTabUserById(id);
        if(null == userVo){
            return result.failure(-1,"分配对象不存在");
        }
        sysUserMapper.deleteTabUserProject(id.toString());
        if(null != projectIds){
            String[] ids = projectIds.split(",");
            for (String str:ids) {
                sysUserMapper.insertTabUserProject(id.toString(),str);
            }
        }
        return result.success("分配成功");
    }

    @Override
    public Result cascadeSelectArea(String areaParent) {
        if(null == areaParent){
            areaParent = "0";
        }
        List<TabArea> list = tabAreaMapper.getNextById(areaParent);
        return new Result().success(list);
    }

    @Override
    public Result cascadeSelectedArea(Integer id) {
        Result result = new Result();
        if(null != id){
            SysUserVo vo = new SysUserVo();
            vo.setId(id.longValue());
            vo = sysUserMapper.getByUserNameAndPass(vo);
            if(null != vo){
                String str  = sysUserMapper.cascadeSelectedArea(vo.getLevel(),vo.getAreaId());
                if(null != str){
                    String[] arr = str.split(",");
                    result.setData(arr);
                }
            }
        }
        return result;
    }

}
